/*
 * @Author: fk 1031041088@qq.com
 * @Date: 2024-12-11 21:31:07
 * @LastEditors: fk 1031041088@qq.com
 * @LastEditTime: 2024-12-11 23:10:15
 */

let swiper = null;
let currentPage = 1;
let isLoading = false;
let hasMore = true;
const ITEMS_PER_PAGE = 10;

async function loadImages(append = false) {
    if (isLoading || (!append && !hasMore)) return;
    
    try {
        isLoading = true;
        
        // 首次加载时更新浏览次数
        if (currentPage === 1) {
            await fetch('/api/update_views.php');
        }
        
        const response = await fetch(`/api/get_images.php?page=${currentPage}&limit=${ITEMS_PER_PAGE}`);
        const data = await response.json();
        
        if (!append) {
            // 更新图片计数和浏览次数
            document.querySelector('.image-count').textContent = `${data.total} 张照片`;
            document.querySelector('.view-count').textContent = `${data.view_count} 次浏览`;
        }
        
        const gallery = document.getElementById('imageGallery');
        const swiperWrapper = document.querySelector('.swiper-wrapper');
        
        if (!append) {
            gallery.innerHTML = '';
            swiperWrapper.innerHTML = '';
        }
        
        data.images.forEach((image, index) => {
            // 创建相册缩略图
            const imgContainer = document.createElement('div');
            imgContainer.className = 'image-container';
            const globalIndex = (currentPage - 1) * ITEMS_PER_PAGE + index;
            imgContainer.onclick = () => openPreview(globalIndex);
            
            const img = document.createElement('img');
            img.src = image.url;
            img.alt = image.filename;
            
            const timeLabel = document.createElement('div');
            timeLabel.className = 'time-label';
            timeLabel.textContent = new Date(image.created_at).toLocaleString();
            
            const tipLabel = document.createElement('div');
            tipLabel.className = 'tip-label';
            tipLabel.textContent = '长按保存图片';
            
            imgContainer.appendChild(img);
            imgContainer.appendChild(timeLabel);
            imgContainer.appendChild(tipLabel);
            gallery.appendChild(imgContainer);
            
            // 创建轮播图片
            const swiperSlide = document.createElement('div');
            swiperSlide.className = 'swiper-slide';
            const swiperImg = document.createElement('img');
            swiperImg.src = image.url;
            swiperSlide.appendChild(swiperImg);
            swiperWrapper.appendChild(swiperSlide);
        });
        
        // 更新分页状态
        hasMore = data.has_more;
        if (hasMore) {
            currentPage++;
        }
        
        // 初始化或更新Swiper
        if (!append) {
            if (swiper) {
                swiper.destroy();
            }
            initSwiper();
        } else {
            swiper.update();
        }
        
    } catch (error) {
        console.error('加载失败：', error);
    } finally {
        isLoading = false;
    }
}

function initSwiper() {
    swiper = new Swiper('.swiper', {
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
        pagination: {
            el: '.swiper-pagination',
            type: 'fraction',
            formatFractionCurrent: function (number) {
                return '第 ' + number;
            },
            formatFractionTotal: function (number) {
                return ' / ' + number + ' 张';
            },
            renderFraction: function (currentClass, totalClass) {
                return '<span class="' + currentClass + '"></span>' +
                       '<span class="' + totalClass + '"></span>';
            }
        },
        on: {
            slideChange: function () {
                document.querySelector('.swiper-pagination').style.opacity = '1';
            }
        }
    });
}

// 添加滚动监听
function handleScroll() {
    if (isLoading || !hasMore) return;
    
    const scrollHeight = document.documentElement.scrollHeight;
    const scrollTop = window.scrollY || document.documentElement.scrollTop;
    const clientHeight = window.innerHeight || document.documentElement.clientHeight;
    
    // 当距离底部100px时加载更多
    if (scrollHeight - scrollTop - clientHeight < 100) {
        loadImages(true);
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    loadImages();
    window.addEventListener('scroll', handleScroll);
});

function openPreview(index) {
    const modal = document.getElementById('previewModal');
    modal.classList.add('active');
    swiper.slideTo(index, 0);
}

// 关闭预览
document.querySelector('.close-btn').addEventListener('click', () => {
    document.getElementById('previewModal').classList.remove('active');
});

// 点击空白处关闭预览
document.getElementById('previewModal').addEventListener('click', (e) => {
    if (e.target.classList.contains('preview-modal')) {
        e.target.classList.remove('active');
    }
}); 